package implicits

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.http.{ContentTypeOf, ContentTypes, Writeable}
import play.api.mvc.Codec
import upickle.default._

import scala.collection.immutable.SeqMap

/**
 * Created by yz on 11/4/2022
 */
trait UjsonExtraTool {

  implicit def seqMapReadTWrite[T](implicit writer: Writer[T], reader: Reader[T]): ReadWriter[SeqMap[String, T]] = {
    readwriter[ujson.Obj].bimap[SeqMap[String, T]](x => {
      val ts = x.toList.map { case (k, v) =>
        (k, writeJs(v))
      }
      ujson.Obj.from(ts)
    }, y => {
      val ts = y.value.map { case (k, v) =>
        (k, read[T](v))
      }
      SeqMap.from(ts)
    })
  }

  implicit def contentTypeOf_UJson(implicit codec: Codec): ContentTypeOf[ujson.Value] = {
    ContentTypeOf[ujson.Value](Some(ContentTypes.JSON))
  }

  implicit def writeableOf_UJson(implicit codec: Codec): Writeable[ujson.Value] = {
    Writeable(jsval => codec.encode(jsval.toString()))
  }


}
